// mobile bind
// ============

define(['zepto', 'utils', 'JST', 'wxshare'],
function($, utils, JST, wxshare){
  return {
    init: function(data) {
      
      this.model = {
          'scheduleId': data.scheduleId
      }
      
      this.initPage(data)
      
      this.bindAppointmentSubmitAction()
      
    },
    
    initPage: function(data) {
        // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
    },
    
   // order submit evvent handler
    bindAppointmentSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.booking-btn")
      
      
      submitButton.on('click', function(e){
        e.preventDefault();
        
        var hour = $(this).data("hour");
        $('input[name="hour"]').val(hour);
        
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmit(data)
        }
      })
      
    },
    
   // init data
    onInitData: function() {
      return {
        '_method': {
          'value': 'PATCH'
        },
        'scheduleId': {
          'value': this.model.scheduleId,
          'message': '课程不能为空'
        },
        'day': {
          'value': $('input[name="day"]').val().trim(),
          'message': '日期不能为空'
        },
        'hour': {
          'value': $('input[name="hour"]').val(),
          'message': '请勾选上课时间段'
        }
      }
    },
    
    onAppendData: function(data) {
      return data;
    },
    
    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      return true
    },
    
    onSubmit : function(data) {
      
      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      
      $.ajax({
        type:'POST',
        url: window.__CTX__.root + '/profile/course-schedules/' + data.scheduleId.value + '/edit',
        data: processedData
      }).done(function(response){
          $.hidePreloader()
          utils.processResult(response, function(result) {
            $.toast(result.message || "预约成功")
            setTimeout(function() {
              window.location.href = __CTX__.root + "/profile/course-schedules/" + data.scheduleId.value;
            }, 1000)
          }, function(result) {
            $.toast(result.message || '预约失败')
         })
      })
    }
    
  }

})

